/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package GUIExtras;

import java.awt.PopupMenu;
import java.awt.TrayIcon;
import java.awt.SystemTray;
import java.awt.MenuItem;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import jktest.JKMainGui;

/**
 *
 * @author Royce Feng
 */
public class JKSystemTray implements ActionListener {

    private Image trayImage;
    private final PopupMenu popup = new PopupMenu();
    private final TrayIcon trayIcon;
    private final SystemTray tray = SystemTray.getSystemTray();
    private JKMainGui parent;

    /**
     *
     * Constructor for JKSystem tray that accepts a parent parameter. Creates the
     * pop-up menu as well as assigns an actionlistener to the seperate menu items.
     *
     * @param _parent The JKMainGui that is the parent
     */
    public JKSystemTray( JKMainGui _parent ) {
        parent = _parent;

        trayImage = initImage();
        trayIcon = new TrayIcon(initImage());

        // Create a pop-up menu components
        MenuItem aboutItem = new MenuItem("About Me");
        MenuItem exitItem = new MenuItem("Abruptly Exit");

        //Add components to pop-up menu
        popup.add(aboutItem);
        popup.add(exitItem);
        trayIcon.setPopupMenu(popup);
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
        }
        trayIcon.addActionListener(this);
        aboutItem.addActionListener(this);
        exitItem.addActionListener(this);
    }

    /**
     *
     * Removes the icon from the system tray
     *
     */
    public void closeTray() {
        tray.remove(trayIcon);
    }

    public Image getImage() {
        return trayImage;
    }

    /**
     *
     * Calls JKMainGui's MenuItemClicked in order to send the About Me and Abruptly Exit
     * signals
     *
     * @param e The Action Event
     */
    public void actionPerformed( ActionEvent e ) {
        parent.MenuItemClicked(e.getActionCommand());
    }

    private Image initImage() {
        Image img = null;
        URL imageURL = getClass().getResource("jk.jpg");
        if (imageURL == null) {
            System.out.println("No image named");
        } else {
            Toolkit tk = Toolkit.getDefaultToolkit();
            try {
                img = tk.createImage((java.awt.image.ImageProducer) imageURL.getContent());
            } catch (java.io.IOException ex) {
                System.out.println(ex.toString());
            }
        }
        return img;
    }

}
